// subPages/health/evaluation/evaluation.js
const app = getApp()
var util =  require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.id){
      that.setData({
        orderId: options.id
      })
      that.getData(options.id)
      that.getShopData(options.id)
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
        }
      }
    }
    if (!app.globalData.userInfo) {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      app.userInfoReadyCallback = res => {
        if (res) {
          that.setData({
            userInfo: res.userInfo
          });
        }
      }
    }else{
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },

  bindTextArea:function(e){
    // console.log(e)
    var that = this
    var id = e.currentTarget.dataset.id
    var list = that.data.orderList
    for(var i in list){
      if(list[i].id == id){
        list[i].text = e.detail.value
        break;
      }
    }
    this.setData({
      // textArea: e.detail.value
      orderList: list
    })
  },

  //获取数据
  getData:function(id){
    var that = this
    util.getAjax(app.globalData.apiUrl + '/user_get_community_health_shop_order_content',function(res){
      console.log(res)
      if(res.data.length!=0){
        for(var i in res.data){
          res.data[i].evalList = [{ tempFilePaths: [], imgList: [] }];
        }
        that.setData({
          orderList: res.data
        })
      }
    },{order_id: id})
  },

  //获取商户信息
  getShopData:function(id){
    var that = this
    util.getAjax(app.globalData.apiUrl + '/Api/Communityhealth/get_shop_id',function(res){
      console.log(res)
      if(res.data){
        that.setData({
          shopId: res.data.shop_id
        })
      }
    },{order_id: id})
  },
  
  //添加图片
  joinPicture: function (e) {
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var that = this;
    var orderList = that.data.orderList
    for(var i in orderList){
      if(orderList[i].id == id){
        var imgNumber = orderList[i].evalList[index].tempFilePaths;
        break;
      }
    }
    if (imgNumber.length >= 6) {
      util.showModal('提示','最多上传六张图片')
      return;
    }
    // that.setData({
    //   orderList: orderList
    // })
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", imgNumber, id);
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", imgNumber, id);
          }
        }
      }
    })
  },

  //选择图片
  chooseWxImage: function (type, list, id) {
    var img = list;
    var len = img.length;
    var that = this;
    // var evalList = this.data.evalList;
    wx.chooseImage({
      count: 6,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function (res) {
        // console.log(res)
        var addImg = res.tempFilePaths;
        var addLen = addImg.length;
        if ((len + addLen) > 6) {
          for (var i = 0; i < (addLen - len); i++) {
            var str = {};
            str.pic = addImg[i];
            img.push(str);
          }
        } else {
          for (var j = 0; j < addLen; j++) {
            var str = {};
            str.pic = addImg[j];
            img.push(str);
          }
        }
        that.upload(img,id);
      },
    })
  },

  //删除图片
  clearImg: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var orderList = that.data.orderList
    for(var i in orderList){
      if(orderList[i].id == id){
        util.getAjax(app.globalData.apiUrl + '/Api/First/delete',function(res){
          // console.log(res)
          var img = orderList[i].evalList[0].tempFilePaths;
          var img2 = orderList[i].evalList[0].imgList;
          img.splice(index, 1);
          img2.splice(index, 1);
          that.setData({
            orderList: orderList
          })
        },{file: orderList[i].evalList[0].tempFilePaths[index]})
        break;
      }
    }
  },

  //多张图片上传
  upload: function (path,id) {
    var that = this;
    var curImgList = [];
    for (var i = 0; i < path.length; i++) {
      wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      wx.uploadFile({
        url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
        filePath: path[i].pic,
        name: 'img',
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          douploadpic: '1'
        },
        success: function (res) {
          // console.log(res)
          curImgList.push(res.data);
          var orderList = that.data.orderList
          for(var i in orderList){
            if(orderList[i].id == id){
              orderList[i].evalList[0].imgList = curImgList;
              break;
            }
          }
          that.setData({
            // evalList: evalList
            orderList: orderList
          })
        },
        fail: function (e) {
          util.showModal('提示','上传失败')
          return
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
    }
  },

  setImg:function(evalList){
    var that = this 
    var imgPort = [];//图片地址，多张以逗号分割
    if(evalList){
      var imgList = evalList[0].imgList
      for (var j = 0; j < imgList.length; j++) {
        imgPort.push(imgList[j])
      }
    }
    // console.log(imgPort)
    return imgPort
  },

  //发表
  clickBtn:function(){
    var that = this
    var orderList = that.data.orderList
    var arr = []
    for(var i in orderList){
      let list = {
        user_id: that.data.userId,
        content: orderList[i].text?orderList[i].text: '',
        product_id: orderList[i].product_id,
        content_img: that.setImg(orderList[i].evalList),
        order_id: orderList[i].order_id,
        user_name: that.data.userInfo.nickName,
        user_head_img: that.data.userInfo.avatarUrl,
        shop_id: that.data.shopId
      }
      arr.push(list)
    }
    util.postAjax(app.globalData.apiUrl + '/user_tell_community_health_shop_order',function(res){
      // console.log(res)
      if(res.data == 1){
        util.showToast('发表成功','success',2000)
        setTimeout(function(){
          wx.navigateBack({
            delta: 1, // 回退前 delta(默认为1) 页面
          })
        },500)
      }
    },{all_tell: arr,order_id: that.data.orderId})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})